<?php

namespace control;
// 导入模板
class importTemplateClass extends adIndexClass
{
    private const title = '导入模板类';
    private const page = 'importTemplate';


    static public function radio($data, $templateType = 1, $callback = 'templateEdit')
    {
        $result = $change = $attribute = '';
        if (isset($data['change'])) {
            $change = " onchange='" . $data['change'] . "(this)' ";
        }
        // 自定义data 参数
        if (isset($data['data']) && is_array($data['data'])) {
            foreach ($data['data'] as $key => $value) {
                $key       = trim($key);
                $value     = trim($value);
                $attribute .= " data-$key='$value' ";
            }
        }
        if (isset($data['other'])) {
            $attribute .= ' ' . $data['other'];
        }
        $data['value'] = $data['value'] ?? $data['option'];
        //如果用此数组中所有的值组成的数组完全等于此数组，则说明此数组为索引数组，反之为关联数组
        $img        = root . 'img/control/edit.svg';
        $detail        = root . 'img/control/detail.svg';
        foreach ($data['value'] as $value) {
            if (isset($data['checked']) && $value['id'] == $data['checked']) {
                $checked = "checked";
            } else {
                $checked = "";
            }
            if ($callback == 'templateEdit') {
                $click = "templateEdit('" . self::page . "','" . $value['page'] . "','" . $value['classify'] . "','" . $value['id'] . "','" . $templateType . "')";
            } else {
                $cla      = $value['cla'] ?? $value['page'];
                $fun      = $value['fun'] ?? $value['classify'];
                $params   = $value['params'] ?? "{id: '$value[id]'}";
                $click = "$callback('$cla', '$fun', $params)";
            }
            if (isset($value['edit']) && $value['edit'] && (new static())->power('my', "templateEdit")) {
                $editButton = "<img alt='' title='编辑模板' onclick=\"$click\" data-id='$value[id]' class='edit-icon' src='$img'>";
            }else{
                $editButton = "<img alt='' title='查看模板' onclick=\"$click\" data-id='$value[id]' class='edit-icon' src='$detail'>";
            }
            $result .= "<label class='radioLabel'>&nbsp;<input name='" . $data['name'] . "' type='radio' value='" . $value['id'] . "' " . $checked . $change . $attribute . ">&nbsp;" . $value['name'] . "</label>". $editButton;
        }
        return $result;
    }

    /**
     * 导出弹窗
     * @return bool|string
     */
    public function exportFrame(): bool|string
    {
        $cla           = $this->post('cla');//所属页面类
        $exportFun     = $this->post('exportFun') ?: 'exportData';
        $classify      = $this->post('classify') ?: $cla;
        $title         = $this->post('title');
        $checkbox      = $this->post('checkbox') ?: 'listId[]';
        $postData      = [];
        $excludeParams = ['title', 'cla', 'exportFun', 'checkbox']; // 排除掉指定参数，剩下的都是可以传到导入方法中
        foreach ($_POST as $key => $value) {
            if (!in_array($key, $excludeParams)) {
                $postData[$key] = $value;
            }
        }
        $postJsonData    = htmlentities(json_encode($postData, '320'), ENT_QUOTES);
        $add = $this->power('my', "templateEdit") ?
            "<span title='添加导出模板' class='del-row-button' onclick=\"layer('" . self::page . "','addExportTemplate',{cla:'$cla',classify:'$classify'})\">添加</span>" :
            '';
        $templateOption  = $this->templateOption($cla, $classify, 2, '');
        $html            = $this->layerEdit(
            [
                "table"  => [
                    [
                        '选择模板：' => "<span id='template-option'>" . $templateOption . "</span>\n".$add,
                    ],
                ],
                'hidden' => "<div class='hide'></div>",
            ]
        );
        //返回
        return $this->layer([
            "title"  => $title ?: '导出',
            "height" => 200,
            'width'  => 700,
            "html"   => $html,
            'button' => "<input id='exportButton' onclick=\"exportFileDownload('$cla','$exportFun','$checkbox','$postJsonData')\" type='button' class='button' value='导出'>",
        ]);
    }


    /**
     * 导入弹窗
     * @return bool|string
     */
    public function importFrame(): bool|string
    {
        $cla           = $this->post('cla');//所属页面类
        $fun           = $this->post('fun') ?: 'homeSearch';//刷新的列表
        $importFun     = $this->post('importFun') ?: 'importData';
        $exportFun     = $this->post('exportFun') ?: 'downloadModel';
        $classify      = $this->post('classify') ?: $cla;
        $title         = $this->post('title');
        $postData      = [];
        $excludeParams = ['title', 'cla', 'importFun', 'exportFun', 'fun']; // 排除掉指定参数，剩下的都是可以传到导入方法中
        foreach ($_POST as $key => $value) {
            if (!in_array($key, $excludeParams)) {
                $postData[$key] = $value;
            }
        }
        $postJsonData    = htmlentities(json_encode($postData, '320'), ENT_QUOTES);
        $add = $this->power('my', "templateEdit") ?
            "<span title='添加导入模板' class='del-row-button' onclick=\"layer('" . self::page . "','addImportTemplate',{cla:'$cla',classify:'$classify'})\">添加</span>" :
            '';
        $templateOption  = $this->templateOption($cla, $classify, 1, '');
        $html            = $this->layerEdit(
            [
                "table"  => [
                    [
                        '选择模板：' => "<span id='template-option'>" . $templateOption . "</span>\n".$add,
                    ],
                    [
                        '导入模板：' => "<span class='del-row-button' onclick=\"downloadImportTemplate('$cla','$exportFun','$postJsonData')\">点击下载模板</span>",
                    ],
                    [
                        '选择导入文件：' => "<div class='import-frame-file-title'><span class='spanButton' onclick=\"$('#importFile').click()\">选择文件</span><span class='file-name'></span></div>",
                    ],
                    [
                        '温馨提示：' => para('importTip'),
                    ],
                ],
                'hidden' => "<div class='hide'><input name='file' id='importFile' type='file' onchange='setFileName(this)'></div><div id='progressBarId' class='progressBar'></div>",
            ]
        );
        //返回
        return $this->layer([
            "title"  => $title ?: '导入',
            "height" => 300,
            'width'  => 700,
            "html"   => $html,
            'button' => "<input data-fun='$fun' id='importButton' onclick=\"fileUpload('$cla','$importFun','$postJsonData')\" type='button' class='button' value='导入文件'>",
        ]);
    }

    public function addImportTemplate()
    {
        $id         = $this->post('id');
        $info       = query('import_template', "id = '$id'");
        $cla        = $this->post('cla');
        $classify   = $this->post('classify');
        $edit = ($id != 'sysTemplate' && $this->power('my', "templateEdit"));  // 是否编辑
        $disabledAttr = $edit ? '' : 'disabled';
        // 初始化字段
        $className  = $cla . 'Class';
        $obj        = new  (__NAMESPACE__ . '\\' . $className)();
        $initArray = $obj->importFieldInit($classify);
        // 模板字段
        $templateField = self::templateField($cla, 'importFieldInit', $classify, $info['id']);
        // 查看是否增加了字段
        $initName = array_column($initArray, 'columnName');
        $templateName = array_column($templateField, 'columnName');
        $extraValues = array_diff($initName, $templateName);
        if(count((array)$extraValues) > 0) {
            foreach ((array)$extraValues as $key) {
                // 寻找新增字段在数组中的位置
                $keyIndex         = array_search($key, $initName);
                $array            = $initArray[$keyIndex];
                $array['id'] = '';
                $array['display'] = 0;
                $templateField[] = $array;
            }
        }
        $body         = '';
        $checkAllBool = "checked";
        foreach ($templateField as $index => $array) {
            $other = " onchange='templateBoxChange()' data-name='$array[columnName]' ";
            if (isset($array['display']) && $array['display']) {
                $other .= " checked ";
            } else {
                $checkAllBool = '';
            }
            //判断是否是必选项
            $title = '';
            if (self::getIsMustValue($initArray, $array['columnName'])){
                $other .= "disabled class='radioDisabled'";
                $title = '必填项';
            }
            $check      = $this->dominate(["box" => ["title" => $title, "other" => $other.$disabledAttr, "name" => "columnId", "value" => $array['id'] ?: suiji()]]);
            $columnName = $array['columnName'];
            $repeat     = self::getInitField($initArray, $array['columnName'], 'isRepeat');
            if ($repeat) {
                $columnName = "<span title='排重项' class='yellow'>{$array['columnName']}</span>";
            }
            $aliasName = $array['aliasName']??$array['columnName'];
            $list = $index + 1;
            $body .= "
		    <ul>
		        <li>" . $check . "</li>
		        <li>" . $columnName . hidden(['name' => 'columnName', 'value' => $array['columnName']]) . "</li>
		        <li>" . ($edit ? text(["name" => "aliasName", "value" => $aliasName]) : $aliasName) . "</li>
		        <li>" . ($edit ? text(["type" => "number", "name" => "list", "change" => "installList", "value" => $list, "other" => " min='0' max='1000000' step='1' "]) : $list) . "</li>
		    </ul>
		    ";
        }

        $delButton = "<div class='restoreDefault del-template' onclick=\"templateDel(this)\">删除</div>";
        if (empty($info['id']) || !$info['isDel'] || !$this->power('my', "templateDel")) {
            $delButton = '';
        }
        $editButton = "<div class='restoreDefault' onclick=\"templateReset(this)\">重置</div>
    		<div class='confirm' onclick=\"templateConfirm(this)\">确定</div>";
        if (!$edit) {
            $editButton = '';
        }
        $name = $edit ? text(["name" => "templateName", 'class' => 'width150', "title" => "请填写模板名称", 'value' => $info['name']]) : ($info['name']?:'默认');
        $html = "
        <style>
		  
        </style>
        <form name='templateForm' class='install'  onsubmit='return false'>
    		<ul class='menu'>
    		    <li>
    		        <label title='全选' class='listCheckbox'>
    		            <input type='checkbox' $checkAllBool $disabledAttr name='columnId' form='templateForm' onchange=\"templatecheckAll(this)\">
    		            <span></span>
                    </label>
                </li>
    		    <li>列名称</li>
    		    <li>别名</li>
    		    <li>序号</li>
    		</ul>
    		<div class='body'>" . $body . "</div>
    		<div class='foot'>模板名称：" .
            $name.
            hidden(['name' => 'id', 'value' => $info['id']]) .
            hidden(['name' => 'page', 'value' => $cla]) .
            hidden(['name' => 'classify', 'value' => $classify]) . "
    		</div>
    		$delButton
    		$editButton
		</form>
        ";
        //返回
        return $this->layer(["title" => ($edit ? '编辑' : '查看').'导入模板', 'zindex' => 10, "height" => 510, "html" => $html, "button" => false]);
    }

    /**
     * 获取导入模板中指定列的isMust值
     * @param $array
     * @param $columnName
     * @return bool
     */
    public static function getIsMustValue($array, $columnName): bool
    {
        foreach ($array as $item) {
            if ($item['columnName'] === $columnName) {
                return $item['isMust']??false;
            }
        }
        return false;
    }

    /**
     * 获取初始化导入数组的某一个字段的值
     * @param $array
     * @param $columnName
     * @param $fieldName
     * @return bool
     */
    public static function getInitField($array, $columnName, $fieldName): bool
    {
        foreach ($array as $item) {
            if ($item['columnName'] === $columnName) {
                return $item[$fieldName] ?? '';
            }
        }
        return false;
    }

    /**
     * 重置导入模板
     * @return false|string
     */
    public function templateReset()
    {
        $cla          = $this->post('page');
        $templateType = $this->post('templateType') ?: 1;
        if (!$this->power('my', "templateEdit")) {
            $json['warn'] = "你没有模板的编辑的权限";
        } elseif (empty($cla)) {
            $json['warn'] = '未找到模板所属页面';
        } else {
            $className = $cla . 'Class';
            $obj       = new  (__NAMESPACE__ . '\\' . $className)();
            if ($templateType == 1) {
                //导入
                $fieldArray = $obj->importFieldInit();
                $initArray  = $fieldArray;
                $body       = '';
                foreach ($fieldArray as $index => $array) {
                    $disabled = '';
                    if (isset($array['isMust']) && $array['isMust']) {
                        $disabled = "disabled class='radioDisabled'";
                    }
                    $other = " onchange='templateBoxChange()' data-name='$array[columnName]' checked $disabled";
                    $check = $this->dominate(["box" => ["title" => "", "other" => $other, "name" => "columnId", "value" => suiji()]]);

                    $columnName = $array['columnName'];
                    $repeat     = self::getInitField($initArray, $array['columnName'], 'isRepeat');
                    if ($repeat) {
                        $columnName = "<span title='排重项' class='yellow'>{$array['columnName']}</span>";
                    }
                    $body .= "
		    <ul>
		        <li>" . $check . "</li>
		        <li>" . $columnName . hidden(['name' => 'columnName', 'value' => $array['columnName']]) . "</li>
		        <li>" . text(["name" => "aliasName", "value" => $array['aliasName']??$array['columnName']]) . "</li>
		        <li>" . text(["type" => "number", "name" => "list", "change" => "installList", "value" => $index + 1, "other" => " min='0' max='1000000' step='1' "]) . "</li>
		    </ul>
		    ";
                }
            } else {
                //导出
                $fieldArray = $obj->exportFieldInit();
                $body       = '';
                foreach ($fieldArray as $index => $array) {
                    $other = " onchange='templateBoxChange()' data-name='$array[columnName]' checked";
                    $check = $this->dominate(["box" => ["title" => "", "other" => $other, "name" => "columnId", "value" => suiji()]]);
                    $body  .= "
		    <ul>
		        <li>" . $check . "</li>
		        <li>" . $array['columnName'] . hidden(['name' => 'columnName', 'value' => $array['columnName']]) . "</li>
		        <li>" . text(["name" => "aliasName", "value" => $array['aliasName']??$array['columnName']]) . "</li>
		        <li>" . text(["type" => "number", "name" => "list", "change" => "installList", "value" => $index + 1, "other" => " min='0' max='1000000' step='1' "]) . "</li>
		    </ul>
		    ";

                }
            }
            $json['warn'] = 2;
            $json['html'] = $body;
        }
        return json_encode($json, 320);
    }

    /**
     * 模板保存
     * @return false|string
     */
    public function templateConfirm()
    {
        $id         = $this->post('id') ?: suiji();
        $list       = $this->post('install');
        $field      = [
            'type'     => $this->post('templateType') ?: 1,
            'name'     => $this->post('templateName'),
            'page'     => $this->post('page'),
            'classify' => $this->post('classify'),
        ];
        $annotation = [
            'name'     => '模板名称',
            'page'     => '模板所属页面',
            'classify' => '模板类型',
        ];
        $rules      = [
            'name'     => 'required',
            'page'     => 'required',
            'classify' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query('import_template', "id = '$id'");
        if (!$this->power('my', "templateEdit")) {
            $json['warn'] = "你没有模板的编辑的权限";
        } elseif (empty($list)) {
            $json['warn'] = '请选择所需的字段';
        } elseif (self::total(['table' => 'import_template', 'where' => "page = '$field[page]' and name = '$field[name]' and type = $field[type] and classify = '$field[classify]' and id !='$id'"]) > 0 || $field['name'] == '默认') {
            $json['warn'] = '已有此名称的模板了';
        } else {
            $this->startTrans();
            if (empty($info['id'])) {
                $field        = array_merge($field, [
                    'id'    => $id,
                    'stid'  => self::$stid,
                    'isDel' => 1,
                ]);
                $json['warn'] = self::insert([
                    'table' => 'import_template',
                    'field' => $field,
                ]);
            } else {
                $json['warn'] = self::update([
                    'table' => 'import_template',
                    'field' => $field,
                    'where' => "id = '$info[id]'",
                ]);
            }

            delete(['table' => 'import_template_detail', 'where' => "orderId = '$id'"]);
            foreach ($list as $columnId => $array) {
                $mxField    = [
                    'id'         => $columnId,
                    'orderId'    => $id,
                    'columnName' => $array['columnName'],
                    'aliasName'  => $array['aliasName'] ?: $array['columnName'],
                    'list'       => $array['list'],
                    'display'    => $array['display'],
                ];
                $annotation = [
                    'id'         => 'ID',
                    'orderId'    => '模板ID',
                    'columnName' => '列名称',
                    'list'       => '排序号',
                ];
                $rules      = [
                    'id'         => 'required',
                    'orderId'    => 'required',
                    'columnName' => 'required',
                    'list'       => 'required',
                ];
                $result     = $vt->setAliases($annotation)->validate($mxField, $rules)->isOk();
                if ($result === false) {
                    $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
                } elseif (self::total(['table' => 'import_template_detail', 'where' => "orderId = '$id' and aliasName = '$mxField[aliasName]' and id !='$mxField[id]'"]) > 0) {
                    $json['warn'] = "别名【{$mxField['aliasName']}】重复了，请换成其它的名字吧";
                } else {
                    $warn = self::insert([
                        'table' => 'import_template_detail',
                        'field' => $mxField,
                    ]);
                    if ($warn != '新增成功') {
                        $json['warn'] = '模板明细添加失败';
                        break;
                    }
                }

            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                $type         = match ($field['type']) {
                    1       => '导入模板',
                    default => '导出模板'
                };
                $json['html'] = $this->templateOption($field['page'], $field['classify'], $field['type'], $id);
                $operation    = mb_substr($json['warn'], 0, 2, 'utf-8');
                //添加日志
                $text = $this->control['name'] . $operation . "了" . $type . "【" . $info['name'] . "】";
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $json['msg']  = $json['warn'];
                $json['warn'] = 2;
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 模板选项
     * @param $page
     * @param $classify
     * @param int $type
     * @param string $value
     * @return string
     */
    public function templateOption($page, $classify, $type = 1, $value = ''): string
    {
        $import_template_all = find(['table' => 'import_template', 'where' => "page = '$page' and classify = '$classify' and type = $type order by time asc"]);
        $templateOption      = [];
        $templateOption['sysTemplate'] = [
            'id'       => 'sysTemplate',
            'edit'     => 0,
            'name'     => '默认',
            'page'     => $page,
            'classify' => $classify,
        ];
        if(is_array($import_template_all['array']) && count($import_template_all['array']) > 0){
            foreach ($import_template_all['array'] as $array) {
                if($array['isDefault']){
                    $value = $array['id'];
                }
                $templateOption[$array['id']] = [
                    'id'       => $array['id'],
                    'edit'     => 1,
                    'name'     => $array['name'],
                    'page'     => $array['page'],
                    'classify' => $array['classify'],
                ];
            }
        }
        return $this->radio(['name' => 'templateId', 'value' => $templateOption, 'checked' => $value?:'sysTemplate'], $type);
    }

    /**
     * 导入导出重置默认模板
     * @return false|string
     */
    public function templateDefault()
    {
        $templateId   = $this->post('templateId');
        $info = query('import_template', "id = '$templateId'");
        if (empty($info['id'])) {
            $json['warn'] = '未找到此模板';
        } else {
            self::update([
                'table' => 'import_template',
                'field' => ['isDefault'=>0],
                'where' => "page = '$info[page]' and classify = '$info[classify]' and type = '$info[type]'",
            ]);
            self::update([
                'table' => 'import_template',
                'field' => ['isDefault'=>1],
                'where' => "id = '$info[id]'",
            ]);
            $json['warn'] = 2;
        }
        resp:
        return json_encode($json, 320);

    }

    /**
     * 模板删除
     * @return false|string
     */
    public function templateDel()
    {
        $id   = $this->post('id');
        $info = query('import_template', "id = '$id'");
        if (!$this->power('my', "templateDel")) {
            $json['warn'] = "你没有模板的删除的权限";
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此模板';
        } elseif (!$info['isDel']) {
            $json['warn'] = "此模板不可删除";
        } else {
            $json['warn'] = delete(['table' => 'import_template', 'where' => "id = '$info[id]'"]);
            if (in_array($json['warn'], ["删除成功"])) {
                $type = match ($info['type']) {
                    1       => '导入模板',
                    default => '导出模板'
                };
                //更新文件
                delete(['table' => 'import_template_detail', 'where' => "orderId = '$info[id]'"]);
                //添加日志
                $text = $this->control['name'] . "删除了" . $type . "【" . $info['name'] . "】";
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $json['warn'] = 2;
                $json['msg']  = '删除成功';
            }
        }

        resp:
        return json_encode($json, 320);

    }

    /**
     * 导入结果
     * @return bool|string
     */
    public function importResultMessage(): bool|string
    {
        $text  = $this->post('text');
        $title = $this->post('title');
        $text  = neirong(html_entity_decode($text, ENT_QUOTES));
        $html  = <<<eof
<div class="import-result-box">
    <div class="import-result-title">$title</div>
    <div class="import-result-content">
    $text
    </div>
</div>
<style>
.import-result-box{display: flex;flex-direction: column;height: 100%;}
.import-result-box .import-result-title{border-bottom: 1px solid #e6e6e6;padding: 10px;font-weight: 600}
.import-result-box .import-result-content{flex: 1;height: 100%;overflow: auto;padding: 10px}
</style>
eof;

        //返回
        return $this->layer(["title" => '导入结果', "height" => 500, 'winFix' => true, 'width' => 800, "html" => $html, "zindex" => 3, "button" => false]);
    }

    public function addExportTemplate()
    {
        $id         = $this->post('id');
        $info       = query('import_template', "id = '$id'");
        $cla        = $this->post('cla');
        $classify   = $this->post('classify');
        $edit = ($id != 'sysTemplate' && $this->power('my', "templateEdit"));  // 是否编辑
        $disabledAttr = $edit ? '' : 'disabled';
        // 初始化字段
        $className  = $cla . 'Class';
        $obj        = new  (__NAMESPACE__ . '\\' . $className)();
        $initArray = $obj->exportFieldInit($classify);
        // 模板字段
        $templateField = self::templateField($cla, 'exportFieldInit', $classify, $info['id']);
        // 查看是否增加了字段
        $initName = array_column($initArray, 'columnName');
        $templateName = array_column($templateField, 'columnName');
        $extraValues = array_diff($initName, $templateName);
        if(count((array)$extraValues) > 0) {
            foreach ((array)$extraValues as $key) {
                // 寻找新增字段在数组中的位置
                $keyIndex         = array_search($key, $initName);
                $array            = $initArray[$keyIndex];
                $array['id'] = '';
                $array['display'] = 0;
                $templateField[] = $array;
            }
        }
        $body         = '';
        $checkAllBool = "checked";
        foreach ($templateField as $index => $array) {
            $other = " onchange='templateBoxChange()' data-name='$array[columnName]' ";
            //更新
            if (isset($array['display']) && $array['display']) {
                $other .= " checked ";
            } else {
                $checkAllBool = '';
            }
            $check = $this->dominate(["box" => ["title" => "", "other" => $other.$disabledAttr, "name" => "columnId", "value" => $array['id'] ?: suiji()]]);
            $aliasName = $array['aliasName']??$array['columnName'];
            $list = $index + 1;
            $body  .= "
		    <ul>
		        <li>" . $check . "</li>
		        <li>" . $array['columnName'] . hidden(['name' => 'columnName', 'value' => $array['columnName']]) . "</li>
		        <li>" . ($edit ? text(["name" => "aliasName", "value" => $aliasName]) :  $aliasName). "</li>
		        <li>" . ($edit ? text(["type" => "number", "name" => "list", "change" => "installList", "value" => $list, "other" => " min='0' max='1000000' step='1' "]) :  $list) . "</li>
		    </ul>
		    ";
        }
        $delButton = "<div class='restoreDefault del-template' onclick=\"templateDel(this,2)\">删除</div>";
        if (empty($info['id']) || !$info['isDel'] || !$this->power('my', "templateDel")) {
            $delButton = '';
        }
        $editButton = "<div class='restoreDefault' onclick=\"templateReset(this,2)\">重置</div>
    		<div class='confirm' onclick=\"templateConfirm(this,2)\">确定</div>";
        if (!$edit) {
            $editButton = '';
        }
        $name = $edit ? text(["name" => "templateName", 'class' => 'width150', "title" => "请填写模板名称", 'value' => $info['name']]) : ($info['name']?:'默认');
        $html = "
        <style>
		  
        </style>
        <form name='templateForm' class='install'  onsubmit='return false'>
    		<ul class='menu'>
    		    <li>
    		        <label title='全选' class='listCheckbox'>
    		            <input type='checkbox' $checkAllBool $disabledAttr name='columnId' form='templateForm' onchange=\"templatecheckAll(this)\">
    		            <span></span>
                    </label>
                </li>
    		    <li>列名称</li>
    		    <li>别名</li>
    		    <li>序号</li>
    		</ul>
    		<div class='body'>" . $body . "</div>
    		<div class='foot'>模板名称：" .
            $name .
            hidden(['name' => 'id', 'value' => $info['id']]) .
            hidden(['name' => 'page', 'value' => $cla]) .
            hidden(['name' => 'classify', 'value' => $classify]) . "
    		</div>
    		$delButton
    		$editButton
		</form>
        ";
        //返回
        return $this->layer(["title" => ($edit ? '编辑' : '查看').'导出模板', 'zindex' => 10, "height" => 510, "html" => $html, "button" => false]);
    }

    /**
     * 系统导入模板初始化
     */
    public static function importTemplateInit()
    {
        $cla = [
            'job',
            'topicLibrary',
            'staffProfiles',
            'talentPool',
            'trainingPlan',
            'performanceAim',
            'clockStatistics',
            'insure',
            'personalTax',
            'laborCompany',
            'resource',
            'driver',
            'meeting',
            'dossier',
            'visitor',
            'cashBook',
            'bankBook',
            'innerTransfer',
            'assetManagement',
            'initialization',
            'voucher',
            'productLine',
            'process',
            'routing',
            'kehuStaff',
            'clientPool',
            'client',
            'clue',
            'cluePool',
            'opportunity',
            'saleOrder',
            'purchaseOrder',
            'logisticsDriver',
            'logisticsCar',
            'outStockExec',
            'inStockExec',
            'inventory',
            'material',
            'bom',
            'clientProfile',
            'clientPriceList',
            'supplier',
            'supplierPriceList',
            'warehouse',
            'timingReport',
            'machiningOrder',
            'pickOrder',
            'refundMaterialOrder',
            'equipment',
            'parts',
            //'mold',
            'saleInvoice',
            'incomeInvoice',
            'car',
            'workshopClock',
            'subject',
            'laborSalary',
            [
                'inventoryDefault' => [
                    '供应商期初',
                    '客户期初',
                    '库存期初',
                ],
            ],
        ];

        foreach ($cla as $array) {
            if (is_array($array)) {
                foreach ($array as $page => $classifyArr) {
                    $className = $page . 'Class';
                    $obj       = new  (__NAMESPACE__ . '\\' . $className)();
                    foreach ($classifyArr as $value) {
                        $fieldArray = $obj->importFieldInit($value);
                        static::importTemplateInitSetData($fieldArray, $page, 1, $value);
                    }
                }
            } else {
                $className  = $array . 'Class';
                $obj        = new  (__NAMESPACE__ . '\\' . $className)();
                $fieldArray = $obj->importFieldInit();
                static::importTemplateInitSetData($fieldArray, $array);
            }
        }
    }

    /**
     * 系统导出模板初始化
     */
    public static function exportTemplateInit()
    {
        $cla = [
            'job',
            'topicLibrary',
            'staffProfiles',
            'talentPool',
            'trainingPlan',
            'examRecord',
            'performanceAim',
            'clockStatistics',
            'insure',
            'laborCompany',
            'resource',
            'driver',
            'meeting',
            'dossier',
            'visitor',
            'cashBook',
            'bankBook',
            'innerTransfer',
            'assetManagement',
            'initialization',
            'voucher',
            'kehuStaff',
            'clientPool',
            'client',
            'clue',
            'cluePool',
            'opportunity',
            'logisticsDriver',
            'logisticsCar',
            'outStockExec',
            'inStockExec',
            'inventory',
            'material',
            'bom',
            'clientProfile',
            'clientPriceList',
            'supplier',
            'supplierPriceList',
            'timingReport',
            'parts',
            'mold',
            'saleInvoice',
            'incomeInvoice',
            'workAdd',
            'labor',
            'laborSettle',
            'carFee',
            'stampRecord',
            'mealOrderRecord',
            'takeMealRecord',
            'mealStatistics',
            'canteenPay',
            'canteenEvaluate',
            'inspectionDetail',
            'checkStatistics',
            'follow',
            'paybackPlan',
            'saleTrack',
            'saleOrderMx',
            'saleIncome',
            'saleProfit',
            'supplyList',
            'outsourceList',
            'outsourceProcessTrack',
            'outsourcePickMx',
            'outsourceCost',
            'aftermarketStatistics',
            'inStock',
            'outStock',
            'toolOverhaulOut',
            'inventoryBalance',
            'batchDetail',
            'inventoryDistribution',
            'receiptDelivery',
            'receiptDeliverySummary',
            'materialDetail',
            'warehousePosition',
            'machiningCard',
            'workshopClock',
            'tempInventory',
            'materialInspectionStatistics',
            'outsourceInspectionStatistics',
            'processingInspectionStatistics',
            'processSpotCheckStatistics',
            'processInspectionStatistics',
            'shippingInspectionStatistics',
            'badAnalysis',
            'moldDisarmament',
            'moldReduction',
            'pieceCount',
            'pieceHour',
            'pieceStatistics',
            'costCount',
            'costCountStatistics',
            'productTrack',
            'completionRate',
            'pickAndRefundMx',
            'productDiff',
            'processReportStatistics',
            'processInventory',
            'contactStaff',
            'currentUnitBalance',
            'clientReconciliation',
            'supplierReconciliation',
            'incomeDetails',
            'payDetails',
            'incomeAgeAnalysis',
            'payAgeAnalysis',
            'otherDetails',
            'laborSalary',
            [
                'currentUnitMx' => [
                    '客户一览表',
                    '供应商一览表',
                ],
            ],
            [
                'toolCollection' => [
                    '工具领用',
                    '工具领用归还明细',
                ],
            ],
            [
                'freightDetails' => [
                    '内部车辆运费明细',
                    '外调车辆运费明细',
                ],
            ],
            [
                'outsourceDiff' => [
                    '委外用料差异明细',
                    '委外用料差异汇总',
                ],
            ],
            [
                'purchaseStatistics' => [
                    '采购商品汇总',
                    '采购供应商汇总',
                ],
            ],
            [
                'saleStatistics' => [
                    '销售商品汇总',
                    '销售客户汇总',
                    '销售员汇总',
                ],
            ],
            [
                'car' => [
                    '车辆档案',
                    '费用汇总',
                ],
            ],
            [
                'inventoryDefault' => [
                    '供应商期初',
                    '客户期初',
                    '库存期初',
                ],
            ],
            [
                'paySlip' => [
                    '待拨付',
                    '已拨付',
                ],
            ],
            [
                'inspectionDetail' => [
                    '待通知',
                    '已通知',
                    '已反馈',
                    '验证通过',
                    '验证未过',
                    '已关闭',
                    '全部',
                ],
            ],
            [
                'materialDemand' => [
                    '材料需求计划明细',
                    '按日期汇总材料需求',
                    '按物料汇总材料需求',
                ],
            ],
        ];
        foreach ($cla as $array) {
            if (is_array($array)) {
                foreach ($array as $page => $classifyArr) {
                    $className = $page . 'Class';
                    $obj       = new  (__NAMESPACE__ . '\\' . $className)();
                    foreach ($classifyArr as $value) {
                        $fieldArray = $obj->exportFieldInit($value);
                        static::importTemplateInitSetData($fieldArray, $page, 2, $value);
                    }
                }
            } else {
                $className = $array . 'Class';
                $obj       = new  (__NAMESPACE__ . '\\' . $className)();
                try {
                    $fieldArray = $obj->exportFieldInit();
                    static::importTemplateInitSetData($fieldArray, $array, 2);
                } catch (\Throwable $e) {

                }
            }
        }
    }

    /**
     * 模板初始化数据
     * @param $fieldArray
     * @param $page
     * @param int $type
     * @param string $classify
     */
    public static function importTemplateInitSetData($fieldArray, $page, $type = 1, $classify = '')
    {
        $classify = $classify ?: $page;
        if (self::total(['table' => 'import_template', 'where' => "page = '$page' and type = $type and classify = '$classify' and isDel = 0"]) == 0) {
            //没有默认模板时，生成默认
            $field = [
                'id'       => suiji(),
                'stid'     => self::$stid,
                'isDel'    => 0,
                'type'     => $type,
                'name'     => '默认',
                'page'     => $page,
                'classify' => $classify,
            ];
            self::insert([
                'table' => 'import_template',
                'field' => $field,
            ]);
            foreach ($fieldArray as $index => $array) {
                self::insert([
                    'table' => 'import_template_detail',
                    'field' => [
                        'id'         => suiji(),
                        'orderId'    => $field['id'],
                        'columnName' => $array['columnName'],
                        'aliasName'  => $array['aliasName'] ?: $array['columnName'],
                        'list'       => $index + 1,
                        'display'    => 1,
                    ],
                ]);
            }
        }
    }

    /**
     * 导入模板按钮
     * @param $cla
     * @param string $fun
     * @return string
     */
    public static function importTemplateButton($cla, $fun = 'downloadModel'): string
    {
        return "<a href='" . root . "control/adIndex.php?cla=" . $cla . "&fun={$fun}'><span class='spanButton'>导入模板</span></a>";
    }

    /**
     * Desc : 获取导入导出字段
     * User : you name
     * Date : 2024-05-22 09:46
     * @param $cla
     * @param $fun //模板初始化方法
     * @param string $classify
     * @param string $id
     * @return array|mixed
     */
    public static function templateField($cla, $fun, $classify = '', $id = '')
    {
        // 初始字段
        $className  = $cla . 'Class';
        if (!method_exists(__NAMESPACE__ . '\\' . $className, $fun)) {
            return [];
        }
        $obj        = new  (__NAMESPACE__ . '\\' . $className)();
        $initArray = $obj->$fun($classify);

        $importTemplate = query('import_template', "id = '$id'");
        if($importTemplate['id']) {
            // 模板内容
            $initName = array_column($initArray,'columnName');
            $all = find([
                'table' => 'import_template_detail',
                'field' => 'id,columnName,aliasName,display',
                'where' => "orderId = '$importTemplate[id]' order by list asc"
            ]);
            // 删除初始化中已经不存在的字段
            return array_filter(array_map(function($item) use ($initName) {
                if(in_array($item['columnName'], $initName)) {
                    $item['columnName'] = html_entity_decode($item['columnName']);
                    $item['aliasName'] = html_entity_decode($item['aliasName']);
                    return $item;
                }
            }, $all['array']));
        }else{
            // 初始化模板
            return array_map(function($item) {
                $item['id'] = '';
                $item['aliasName'] = !empty($item['aliasName']??'') ? html_entity_decode($item['aliasName']) : html_entity_decode($item['columnName']);
                $item['display'] = 1; // 加上显示字段
                return $item;
            }, $initArray);
        }
    }

    /**
     * 获取模板名称
     * @param $id
     * @return string
     */
    public static function getName($id): string
    {
        $name = '默认';
        $importTemplate = query('import_template', "id = '$id'", "id,name");
        if ($importTemplate['id']) {
            $name = $importTemplate['name'];
        }
        return $name;
    }

    /**
     * Desc : 组合导入表头
     * User : you name
     * Date : 2024-05-22 10:49
     * @param $templateField
     * @param $row
     * @return array
     */
    public static function combinHead($templateField, $row): array
    {
        $templateFieldName = array_column($templateField,'aliasName'); // 别名一维数组
        $headArray = [];
        $row = formSubArray($row);
        // 将表头的html实体转为字符，以便于进行准确比较
        $row = array_map(function($string) {
            return html_entity_decode($string, ENT_QUOTES, 'UTF-8');
        }, $row);
        foreach ($row as $index => $value) {
            $key         = array_search($value, $templateFieldName);
            $detail = $templateField[$key];
            if (!empty($detail['columnName']??'') && !empty($detail['display']??'') && $key !== false) {
                $headArray[$index] = $detail['columnName'];
            }
        }
        return $headArray;
    }

    public function aa()
    {
        $title  = ["*科目编码", "*科目名称", '*类别', '*余额方向(借/贷)', '数量核算', '辅助核算', '外币核算'];
        $html  = '';
        $bb    = '';
        $cc    = '';
        foreach ($title as $k => $val) {
            $val  = ltrim($val, '*');
            $html .= <<<eof
[
  <br>'columnName'=>'{$val}',
  <br>'aliasName'=>'{$val}',<br>
],<br>
eof;
            $bb   .= <<<eof
 '$val'=>\$array['aaaa'],<br>
eof;

            $cc .= <<<eof
 '$val'=>\$example[$k],<br>
eof;

        }
        //        print_r($cc);
        print_r($bb);
        print_r($html);
        die(0);
    }

    public function cc()
    {
        $cc  = '';
        $all = find(['table' => 'import_template_detail', 'where' => "orderId in (select id from import_template where type = 1 and name = '默认' and page = 'subject' and classify = 'subject') order by list asc"]);
        foreach ($all['array'] as $k => $array) {
            $cc .= <<<eof
 '{$array['columnName']}'=>\$example[$k],<br>
eof;
        }
        print_r($cc);
        die(0);
    }
}
